package org.igeek.atomqq.activity;

import org.igeek.atomqq.AtomQQApplication;
import org.igeek.atomqq.R;
import org.igeek.atomqq.domain.User;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.task.CheckcodeImageTask;
import org.igeek.atomqq.task.CheckcodeImageTask.CheckCodeResponse;
import org.igeek.atomqq.task.CheckcodeStringTask;
import org.igeek.atomqq.task.LoginTask;
import org.igeek.atomqq.task.TaskResultListener;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/** 
 * 登陆窗口 
 * @author <a href="http://hangxin1940.cnblogs.com">hangxin1940@gmail.com</a>
 * @time 2012-2-1 下午03:20:32 
 */
public class Login extends BaseActivity implements OnClickListener,TaskResultListener,DialogInterface.OnKeyListener {
	
	private static final String LOG_TAG="atomqq";
	
	private static final int DIALOG_PROGRESS=0x8;
	
	private static final int FLAG_CHECKCODE_STRING=0x0;
	private static final int FLAG_CHECKCODE_IMAGE=0x1;;
	private static final int FLAG_LOGIN=0x2;
	
	private static final String ONLINE="online";
	private static final String AWAY="away";
	private static final String INVISIBLE="invisible";
	private static final String OFFLINE="offline";
	
	private EditText etUin;
	private EditText etPasswd;
	private EditText etCheckcode;
	private Button btnLoginStatus;
	private Button btnLoginSetting;
	private Button btnLogin;
	private LinearLayout llCheckcode;
	private ImageView ivCheckcode;
	private ProgressBar pbCheckcode;
	
	private Dialog dialog;
	
	private CheckcodeStringTask taskCheckcodeString;
	private CheckcodeImageTask taskCheckcodeImage;
	private LoginTask taskLogin;

	
	private String status;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //获得当前登录用户
		User currentUser=((AtomQQApplication)getApplication()).getCurrentUser();
		
		
		//如果本地不存在当前用户信息，则从网络获取
		if(null!=currentUser){
			Intent intent=new Intent(this,Main.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("uin", currentUser.getUin());
			startActivity(intent);
			finish();
		}
        
        
        setContentView(R.layout.activity_login);
        
        etUin=(EditText) findViewById(R.id.login_etUin);
        etPasswd=(EditText) findViewById(R.id.login_etPasswd);
        etCheckcode=(EditText) findViewById(R.id.login_etCheckcode);
        btnLogin=(Button) findViewById(R.id.login_btnLogin);
        btnLoginSetting=(Button) findViewById(R.id.login_btnLoginSetting);
        btnLoginStatus=(Button) findViewById(R.id.login_btnLoginStatus);
        llCheckcode=(LinearLayout) findViewById(R.id.login_llCheckcode);
        ivCheckcode=(ImageView) findViewById(R.id.login_ivCheckcode);
        pbCheckcode=(ProgressBar) findViewById(R.id.login_pbCheckCode);
        
        
        taskCheckcodeString=new CheckcodeStringTask(this);
        taskCheckcodeImage=new CheckcodeImageTask(this);
        taskLogin=new LoginTask(this);
        
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	
    	status=ONLINE;
    	
    	
    	
    	btnLogin.setOnClickListener(this);
    	btnLoginSetting.setOnClickListener(this);
    	btnLoginStatus.setOnClickListener(this);
    	ivCheckcode.setOnClickListener(this);
    	
    	taskCheckcodeImage.setOnTaskResult(this, FLAG_CHECKCODE_IMAGE);
    	taskCheckcodeString.setOnTaskResult(this, FLAG_CHECKCODE_STRING);
    	taskLogin.setOnTaskResult(this, FLAG_LOGIN);
    	
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	
    	btnLogin.setOnClickListener(null);
    	btnLoginSetting.setOnClickListener(null);
    	btnLoginStatus.setOnClickListener(null);
    	ivCheckcode.setOnClickListener(null);
    	
    	taskCheckcodeImage.setOnTaskResult(null, FLAG_CHECKCODE_IMAGE);
    	taskCheckcodeString.setOnTaskResult(null, FLAG_CHECKCODE_STRING);
    	taskLogin.setOnTaskResult(null, FLAG_LOGIN);
    }

    
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.login_btnLogin:
			
			if(taskCheckcodeImage.isFinished()&&taskCheckcodeString.isFinished()&&taskLogin.isFinished()){
				Log.i(LOG_TAG, "开始登陆");
				showDialog(DIALOG_PROGRESS);
				if(etCheckcode.getText().toString().length()<1){
					taskCheckcodeString.setParams(etUin.getText().toString());
					taskCheckcodeString.execute();
					
				}else{
					taskLogin.setParams(status, etUin.getText().toString(), etPasswd.getText().toString(), etCheckcode.getText().toString());
					
				}
			}
			break;

		case R.id.login_btnLoginSetting:
			
			break;
			
		case R.id.login_btnLoginStatus:
			
			break;

		case R.id.login_ivCheckcode:
			if(taskCheckcodeImage.isFinished()&&taskCheckcodeString.isFinished()&&taskLogin.isFinished()){
				pbCheckcode.setVisibility(View.VISIBLE);
				ivCheckcode.setVisibility(View.GONE);
				etCheckcode.setText("");
				taskCheckcodeImage.setParams(etUin.getText().toString(), etCheckcode.getText().toString());
				taskCheckcodeImage.execute();
			}
			
			break;
		}
		
	}


	@Override
	protected Dialog onCreateDialog(int id) {
		dismissAllDialog();
		
		if(id==DIALOG_PROGRESS){
			if(null==dialog){
				dialog= new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
				dialog.setOnKeyListener(this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.dialog_progress);
			}
			((TextView)dialog.findViewById(R.id.dialog_progress_tvMessage)).setText("正在登陆");
			return dialog;
		}else{
			llCheckcode.setVisibility(View.GONE);
			etCheckcode.setText("");
		}
		
		return super.onCreateDialog(id);
		
		
	}
	
	@Override
	protected void dismissAllDialog() {
		super.dismissAllDialog();
		
		if(null!=dialog&&dialog.isShowing())
			dialog.dismiss();
		
	}
	
	@Override
	public void onTaskResult(Response response, int flag) {
		if(null==response)
			return;
		
		
		switch (flag) {
		
		//获取文字验证码任务的返回结果
		case FLAG_CHECKCODE_STRING:
			String checkCode=response.getText();
			
			//提取字符串的验证码
			checkCode = checkCode.substring(checkCode.indexOf(",") + 2,checkCode.lastIndexOf("'"));
			
			etCheckcode.setText(checkCode);
			
			//如果!开头，则不需要获取图形验证码
			if(checkCode.startsWith("!")){
				
				llCheckcode.setVisibility(View.GONE);
				taskLogin.setParams(status, etUin.getText().toString(), etPasswd.getText().toString(), etCheckcode.getText().toString());
				taskLogin.execute();
				
			}else{
				dismissDialog(DIALOG_PROGRESS);
				Log.i(LOG_TAG, "获取图形验证码");
				llCheckcode.setVisibility(View.VISIBLE);
				pbCheckcode.setVisibility(View.VISIBLE);
				ivCheckcode.setVisibility(View.GONE);
				
				
				taskCheckcodeImage.setParams(etUin.getText().toString(), checkCode);
				taskCheckcodeImage.execute();
				
				etCheckcode.setText("");
				
			}
			
			break;
			
		//获取图形验证码任务的返回结果
		case FLAG_CHECKCODE_IMAGE:
			dismissDialog(DIALOG_PROGRESS);
			pbCheckcode.setVisibility(View.GONE);
			ivCheckcode.setVisibility(View.VISIBLE);
			
			Bitmap image=((CheckCodeResponse)response).getBitmap();
			
			ivCheckcode.setImageBitmap(image);
			
			break;
			
		//登陆任务的返回结果
		case FLAG_LOGIN:
			JSONObject resualt=response.getJsonObj();
			Log.i(LOG_TAG, "登陆信息:"+resualt);
			try {
				int rcode= resualt.getInt("retcode");
				
				if(rcode==0){
					JSONObject res=resualt.getJSONObject("result");
					long uin=res.getLong("uin");
					
					String cip=Long.toString(res.getLong("cip"));
					HttpConnection.getCookieManager().addCookie("cip", cip);
					String vfwebqq = res.getString("vfwebqq");
					HttpConnection.getCookieManager().addCookie("vfwebqq", vfwebqq);
					String psessionid =  res.getString("psessionid");
					HttpConnection.getCookieManager().addCookie("psessionid", psessionid);
					
					dismissDialog(DIALOG_PROGRESS);
					Intent intent=new Intent(this,Main.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("uin", uin);
					startActivity(intent);
					finish();
				}else{
					Bundle b=new Bundle();
					b.putString(FLAG_ERROR, "登录出错");
					showDialog(DIALOG_ERROR,b);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Bundle b=new Bundle();
				b.putString(FLAG_ERROR, "服务器返回出错");
				showDialog(DIALOG_ERROR,b);
				
			}
				
			break;
		}
		
	}

	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			if(null!=taskCheckcodeImage)
				taskCheckcodeString.cancel(true);
			if(null!=taskLogin)
				taskLogin.cancel(true);
		}
		return false;
	}


}